package com.hch.datastructure.sparsearray;

import java.util.Arrays;
import java.util.Queue;

public class SparseArray {
    //默认二维数组是矩阵，五子棋问题
    public int[][] originalToSparse(int[][] original) {
        if (original == null || original.length == 0) {
            return null;
        }
        int sum = 0;
        for (int i = 0; i < original.length; i++) {
            for (int j = 0; j < original[0].length; j++) {
                if (original[i][j] != 0) {
                    sum++;
                }
            }
        }
        // 2. 创建对应的稀疏数组
        int sparse[][] = new int[sum + 1][3];
        //行数
        sparse[0][0] = original.length;
        //列数
        sparse[0][1] = original[0].length;
        sparse[0][2] = sum;
        int count = 0; //count 用于记录是第几个非0数据
        for (int i = 0; i < original.length; i++) {
            for (int j = 0; j < original[0].length; j++) {
                if (original[i][j] != 0) {
                    count++;
                    sparse[count][0] = i;
                    sparse[count][1] = j;
                    sparse[count][2] = original[i][j];
                }
            }
        }
        return sparse;
    }

    public int[][] sparseToOriginal(int[][] sparse) {
        if (sparse == null || sparse.length == 0) {
            return null;
        }
//
        int line = sparse[0][0];
        int column = sparse[0][1];
        int[][] original = new int[line][column];
        for (int i = 1; i < sparse.length; i++) {
            original[sparse[i][0]][sparse[i][1]] = sparse[i][2];

        }
        return original;
    }

    public static void main(String[] args) {
        int[][] arr = new int[11][11];
        SparseArray sparseArray = new SparseArray();
        arr[1][2] = 2;
        arr[5][1] = 9;
        arr[0][5] = 7;
        int[][] ints = sparseArray.originalToSparse(arr);
        System.out.println();
        System.out.println("得到稀疏数组为~~~~");
        for (int i = 0; i < ints.length; i++) {
            System.out.printf("%d\t%d\t%d\t\n", ints[i][0], ints[i][1], ints[i][2]);
        }
        System.out.println();
        int[][] ints1 = sparseArray.sparseToOriginal(ints);
        for (int[] row : ints1) {
            for (int data : row) {
                System.out.printf("%d\t", data);
            }
            System.out.println();
        }

    }
}